<template>
  <a-card :body-style="{padding: '24px 32px'}" :bordered='false'>
    <a-form @submit='handleSubmit' :form='form' :label-col='{ span: 4 }' :wrapper-col='{ span: 6 }'>
      <a-tabs :defaultActiveKey='defaultActiveKey' @change='callback'>
        <a-tab-pane tab='企业详情' key='1'>
          <a-form-item style='display:none'>
            <a-input v-decorator="['id']" />
          </a-form-item>
          <a-row>
            <a-col :span='12'>
              <a-form-item :labelCol='labelColHalf' :wrapperCol='wrapperColHalf' label='企业名称'>
                <a-input placeholder='企业名称'
                         v-decorator="['name', {rules: [{required: true, message: '请输入企业名称'}]}]" />
              </a-form-item>
            </a-col>
            <a-col :span='12'>
              <a-form-item :labelCol='labelColHalf' :wrapperCol='wrapperColHalf' label='简称'>
                <a-input placeholder='简称' v-decorator="['shortName']" />
              </a-form-item>
            </a-col>
            <a-col :span='12'>
              <a-form-item :labelCol='labelColHalf' :wrapperCol='wrapperColHalf' label='企业类型'>
                <a-select
                  v-decorator="['type', {initialValue:'COMPANY',rules: [{required: true, message: '请选择企业类型'}]}]">
                  <a-select-option value='COMPANY'>公司</a-select-option>
                  <a-select-option value='PERSON'>个人</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span='12'>
              <a-form-item :labelCol='labelColHalf' :wrapperCol='wrapperColHalf' label='企业状态'>
                <a-select
                  v-decorator="['customerStatus', {initialValue:'DEAL',rules: [{required: true, message: '请选择企业状态'}]}]">
                  <a-select-option value='POTENTIAL'>潜在企业</a-select-option>
                  <a-select-option value='PURPOSE'>意向企业</a-select-option>
                  <a-select-option value='DEAL'>成交企业</a-select-option>
                  <a-select-option value='LOSE'>流失企业</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>

            <a-col :span='12'>
              <a-form-item :labelCol='labelColHalf' :wrapperCol='wrapperColHalf' label='所属地区'>
                <a-select v-decorator="['tenantId', {rules: [{ required: true, message: '请选择所属地区' }]}]"
                          @change='selectTenant'
                          :disabled='tenantEnable'>
                  <a-select-option v-for='item in tenantList' :key='item.id'>{{ item.name }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span='12'>
              <a-form-item :labelCol='labelColHalf' :wrapperCol='wrapperColHalf' label='所属园区'>
                <a-select v-decorator="['parkId', {rules: [{ required: true, message: '请选择所属园区' }]}]"
                          @change='selectPark'
                          :disabled='parkEnable'>
                  <a-select-option v-for='item in parkList' :key='item.id'>{{ item.name }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>

            <a-col :span='12'>
              <a-form-item :labelCol='labelColHalf' :wrapperCol='wrapperColHalf' label='所属楼宇'>
                <a-select v-decorator="['buildingId', {rules: [{ required: true, message: '请选择所属楼宇' }]}]"
                          @change='selectBuilding'>
                  <a-select-option v-for='item in buildingList' :key='item.id'>{{ item.buildingName }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span='12'>
              <a-form-item :labelCol='labelColHalf' :wrapperCol='wrapperColHalf' label='所属楼层'>
                <a-select v-decorator="['buildingDetailIds',{rules: [{ required: true, message: '请选择所属楼层' }]}]"
                          placeholder='所属楼层'
                          mode='multiple'
                          @change='selectBuildingDetail'>
                  <a-select-option v-for='item in buildingDetailList' :key='item.id' :value='item.id'>
                    {{ item.floorName }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>

            <a-col :span='12'>
              <a-form-item :labelCol='labelColHalf' :wrapperCol='wrapperColHalf' label='所属房间'>
                <a-select v-decorator="['roomIds',{rules: [{ required: true, message: '选择所属房间' }]}]"
                          placeholder='所属房间'
                          mode='multiple'>
                  <a-select-option v-for='item in roomList' :key='item.id' :value='item.id'>
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>

            <a-col :span='12'>
              <a-form-item :labelCol='labelColHalf' :wrapperCol='wrapperColHalf' label='入住时间'>
                <a-date-picker
                  format='YYYY-MM-DD HH:mm'
                  valueFormat='YYYY-MM-DD HH:mm:ss'
                  :show-time="{ format: 'HH:mm' }"
                  v-decorator="['startDate',{rules: [{ required: true, message: '选择入住时间' }]}]"
                  type='date'
                  placeholder='入住时间'
                  style='width: 100%'
                />
              </a-form-item>
            </a-col>
            <a-col :span='12'>
              <a-form-item :labelCol='labelColHalf' :wrapperCol='wrapperColHalf' label='租期结束时间'>
                <a-date-picker
                  format='YYYY-MM-DD HH:mm'
                  valueFormat='YYYY-MM-DD HH:mm:ss'
                  :show-time="{ format: 'HH:mm' }"
                  v-decorator="['endDate',{rules: [{ required: true, message: '选择租期结束时间' }]}]"
                  type='date'
                  placeholder='租期结束时间'
                  style='width: 100%'
                />
              </a-form-item>
            </a-col>

            <a-col :span='12'>
              <a-form-item :labelCol='labelColHalf' :wrapperCol='wrapperColHalf' label='所属行业'>
                <a-input placeholder='所属行业' v-decorator="['sector']" />
              </a-form-item>
            </a-col>
            <!--            <a-col :span='12'>-->
            <!--              <a-form-item :labelCol='labelColHalf' :wrapperCol='wrapperColHalf' label='所属国家'>-->
            <!--                <a-input placeholder='所属国家' v-decorator="['country']" />-->
            <!--              </a-form-item>-->
            <!--            </a-col>-->
            <a-col :span='12'>
              <a-form-item :labelCol='labelColHalf' :wrapperCol='wrapperColHalf' label='过程管理'>
                <a-select v-decorator="['process']">
                  <a-select-option value='FIRST_VISIT'>初次拜访</a-select-option>
                  <a-select-option value='NEED_GUID'>需求引导分析</a-select-option>
                  <a-select-option value='COMPETE'>竞争阶段</a-select-option>
                  <a-select-option value='PREDETERMINE'>预定阶段</a-select-option>
                  <a-select-option value='CONTRACT'>合同阶段</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span='12'>
              <a-form-item :labelCol='labelColHalf' :wrapperCol='wrapperColHalf' label='联系人'>
                <a-input placeholder='联系人'
                         v-decorator="['contacts',{rules: [{ required: true, message: '请输入联系人' }]}]" />
              </a-form-item>
            </a-col>
            <a-col :span='12'>
              <a-form-item :labelCol='labelColHalf' :wrapperCol='wrapperColHalf' label='联系电话'>
                <a-input placeholder='联系电话'
                         v-decorator="['phone',{rules: [{ required: true, message: '请输入联系电话' }]}]" />
              </a-form-item>
            </a-col>
            <a-col :span='12'>
              <a-form-item :labelCol='labelColHalf' :wrapperCol='wrapperColHalf' label='邮箱'>
                <a-input placeholder='邮箱' v-decorator="['email']" />
              </a-form-item>
            </a-col>
            <a-col :span='12'>
              <a-form-item :labelCol='labelColHalf' :wrapperCol='wrapperColHalf' label='统一信用代码'>
                <a-input placeholder='统一信用代码' v-decorator="['creditNo']" />
                <a-button type='primary' @click='getQiXinBasicInfo'>同步工商数据</a-button>
              </a-form-item>
            </a-col>
            <a-col :span='12'>
              <a-form-item :labelCol='labelColHalf' :wrapperCol='wrapperColHalf' label='邮编'>
                <a-input placeholder='邮编' v-decorator="['postalCode']" />
              </a-form-item>
            </a-col>
            <a-col :span='24'>
              <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='通讯地址'>
                <a-input placeholder='通讯地址' v-decorator="['mailAddress']" />
              </a-form-item>
            </a-col>
            <a-col :span='24'>
              <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='上传公司logo'
                           extra='尺寸建议：宽160px，高160px'>
                <a-upload
                  v-decorator="['headImg']"
                  list-type='picture-card'
                  class='avatar-uploader'
                  :show-upload-list='false'
                  :action='uploadUrl'
                  :headers='headers'
                  :before-upload='beforeUpload'
                  @change='handleChange'
                >
                  <img v-if='imageUrl' :src='imageUrl' style='width: 102px; height: 102px' />
                  <div v-else>
                    <a-icon :type="loading ? 'loading' : 'plus'" />
                    <div class='ant-upload-text'> 上传</div>
                  </div>
                </a-upload>
              </a-form-item>
            </a-col>
            <a-col :span='24'>
              <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='上传照片墙'>
                <a-upload
                  v-decorator="['bannerImages', {rules: [{ required: false, message: '上传照片墙' }]}]"
                  list-type='picture-card'
                  class='avatar-uploader'
                  :file-list='fileList'
                  :action='uploadUrl'
                  :headers='headers'
                  @preview='handlePreview'
                  @change='handleChangeFileList'
                >
                  <div v-if='fileList.length < 4'>
                    <a-icon type='plus' />
                    <div class='ant-upload-text'> 上传</div>
                  </div>
                </a-upload>
                <a-modal :visible='previewVisible' :footer='null' @cancel='handleCancel'>
                  <img style='width: 100%' :src='previewImage' />
                </a-modal>
              </a-form-item>
            </a-col>
            <a-col :span='8'>
              <a-form-item :labelCol='labelColOneThird' :wrapperCol='wrapperColOneThird' label='渠道类型'>
                <a-select v-decorator="['channelType']">
                  <a-select-option value='AGENT'>中介公司</a-select-option>
                  <a-select-option value='AD'>广告</a-select-option>
                  <a-select-option value='COOPERATE'>合作推荐</a-select-option>
                  <a-select-option value='MY_CHANNEL'>自开发渠道</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span='8'>
              <a-form-item :labelCol='labelColOneThird' :wrapperCol='wrapperColOneThird' label='渠道名称'>
                <a-input placeholder='渠道名称' v-decorator="['channelName']" />
              </a-form-item>
            </a-col>
            <a-col :span='8'>
              <a-form-item :labelCol='labelColOneThird' :wrapperCol='wrapperColOneThird' label='是否黑名单'>
                <a-switch :checked='mdl.isBlacklist' @change='onChangeBlacklist'
                          v-decorator="['isBlacklist']" />
              </a-form-item>
            </a-col>
            <a-col :span='24'>
              <a-form-item :labelCol='labelCol' :wrapperCol='wrapperColOneThird' label='企业备注'>
                <a-input placeholder='企业备注' v-decorator="['remark']" />
              </a-form-item>
            </a-col>
            <a-col :span='24'>
              <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='工商注册号'>
                <a-input placeholder='工商注册号' v-decorator="['regNo']" />
              </a-form-item>
            </a-col>
            <a-col :span='12'>
              <a-form-item :labelCol='labelColHalf' :wrapperCol='wrapperColHalf' label='组织机构代码'>
                <a-input placeholder='组织机构代码' v-decorator="['orgNo']" />
              </a-form-item>
            </a-col>
            <a-col :span='12'>
              <a-form-item :labelCol='labelColHalf' :wrapperCol='wrapperColHalf' label='法人名'>
                <a-input placeholder='法人名' v-decorator="['operName']" />
              </a-form-item>
            </a-col>
            <a-col :span='12'>
              <a-form-item :labelCol='labelColHalf' :wrapperCol='wrapperColHalf' label='经营状态'>
                <a-input placeholder='经营状态' v-decorator="['status']" />
              </a-form-item>
            </a-col>
            <a-col :span='12'>
              <a-form-item :labelCol='labelColHalf' :wrapperCol='wrapperColHalf' label='公司类型(企业性质)'>
                <a-input placeholder='公司类型(企业性质)' v-decorator="['econKind']" />
              </a-form-item>
            </a-col>
            <a-col :span='12'>
              <a-form-item :labelCol='labelColHalf' :wrapperCol='wrapperColHalf' label='注册资金'>
                <a-input placeholder='注册资金' v-decorator="['registCapi']" />
              </a-form-item>
            </a-col>
            <a-col :span='12'>
              <a-form-item :labelCol='labelColHalf' :wrapperCol='wrapperColHalf' label='登记机关'>
                <a-input placeholder='登记机关'
                         v-decorator="['belongOrg']" />
              </a-form-item>
            </a-col>
            <a-col :span='24'>
              <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='注册地址'>
                <a-input placeholder='注册地址'
                         v-decorator="['address']" />
              </a-form-item>
            </a-col>
            <a-col :span='24'>
              <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='经营范围'>
                <!-- <a-input placeholder="经营范围" v-decorator="['scope']" /> -->
                <a-textarea placeholder='经营范围' v-decorator="['scope']"
                            :autoSize='{ minRows: 3, maxRows: 5 }'></a-textarea>
              </a-form-item>
            </a-col>
          </a-row>
          <a-form-item :wrapperCol='{ span: 24 }' style='text-align: center'>
            <a-button htmlType='submit' type='primary'>提交</a-button>
            <a-button icon='rollback' style='margin-left: 8px' @click='rollback'>关闭</a-button>
          </a-form-item>
        </a-tab-pane>
        <a-tab-pane tab='关联合同' key='2' forceRender v-if='$route.query.customerId'>
          <div style='margin: 10px'>
            <a-button type='primary' @click='navContract'>新增合同</a-button>
          </div>
          <a-table
            :pagination='false'
            :columns='contractColumns'
            :dataSource='contractData'
            rowKey='id'
          >
            <div slot='sn' slot-scope='text, record' style='cursor:pointer;color:#1890ff'
                 @click='handleDetail(record.id)'>
              <span>{{ text }}</span>
            </div>
            <span slot='serial' slot-scope='text, record, index'>
              {{ index + 1 }}
            </span>
            <span slot='status' slot-scope='text'>
              {{ text | statusFilter }}
            </span>
          </a-table>
        </a-tab-pane>
        <a-tab-pane tab='企业员工管理' key='3' v-if='$route.query.customerId'>
          <div style='margin: 10px;display:flex; justify-content: flex-start; align-items: flex-start'>
            <a-button type='primary' @click='$refs.contactModal.add({ customerId: $route.query.customerId })'>
              新建企业员工
            </a-button>
            <a-button style='margin-left: 30px' type='success' @click='importUser'>
              导入用户
            </a-button>
            <a-form layout='inline'>
              <a-form-item style='margin-left: 200px;margin-bottom: 20px' label='关键词'>
                <a-input placeholder='请输入关键词' v-model='queryParam.keyword' />
              </a-form-item>
            </a-form>
            <a-button style='margin-left: 30px;margin-top: 3px' type='success' @click='searchData' >
              查询
            </a-button>
          </div>
          <a-table :pagination='true' :columns='contactsItemColumns'
                   :dataSource='contactsItemData'
                   ref='userTable'
                   rowKey='id'>
            <span slot='gender' slot-scope='text, record'>
              {{ record.gender === '1' ? '女' : '男' }}
            </span>
            <span slot='num' slot-scope='text, record'>
                <a @click='handleDeviceTable(record)'>{{ record.num }}</a>
            </span>
            <template slot='operation' slot-scope='text, record'>
              <a-button type='link' @click='$refs.contactModal.add(record)'>编辑</a-button>
              <a-divider type='vertical' />
              <a-popconfirm @confirm='handleDeleteContact(record)'>

                <template slot='title'>
                  <span>确定删除 {{ record.name }} 吗？</span>
                </template>
                <a-icon slot='icon' type='question-circle-o' style='color: red' />
                <a-button type='link'>删除</a-button>
              </a-popconfirm>
            </template>
          </a-table>
        </a-tab-pane>
        <a-tab-pane tab='相关文件' key='4' v-if='$route.query.customerId'>
          <customer-attachment-list :customer-id='$route.query.customerId'></customer-attachment-list>

        </a-tab-pane>
      </a-tabs>
    </a-form>
    <customer-contacts-modal ref='contactModal' @ok='handleContactSaved' />
    <a-modal v-model='visible' title='导入用户' @ok='handleFileOk'>
      <div style='display: flex'>
        <a-upload
          :headers='headers'
          accept='.xlsx,.xls'
          @change='customChange'
          :customRequest='customRequest'>
          <a-button type='primary'>导入用户数据</a-button>
        </a-upload>
        <a-button style='margin-left: 40px' type='primary' @click='exportTemplate'>导出用户模板</a-button>
      </div>

    </a-modal>
    <a-modal v-model='visible1' title='设备授权' width='500px' @ok='itemHandleOk()'>
      <div class='table-page-search-wrapper'>
        <a-form layout='inline'>
          <a-row :gutter='48'>
            <a-col :md='8' :sm='24'>
            <span class='table-page-search-submitButtons'>
<!--              查询有问题-->
              <a-button type='primary' @click='$refs.table.refresh(true)'>查询</a-button>
              <a-button style='margin-left: 8px' @click='() => (deviceQueryParam = {})'>重置</a-button>
            </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <div class='table-operator'>
      </div>
      <a-table
        size='default'
        ref='itemTable'
        rowKey='id'
        :rowSelection='{ selectedRowKeys: selectedDeviceRowKeys, onChange: onDeviceSelectChange }'
        :columns='deviceColumns'
        :dataSource='deviceData'
      >
         <span slot='floorName' slot-scope='text, record'>
              {{ record.roomName ? record.buildName + record.roomName : record.buildName }}
         </span>
      </a-table>
    </a-modal>


  </a-card>
</template>

<script>

import { getTenantList } from '@/api/tenant'
import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import {
  getCustomer,
  getQiXinBasicInfo,
  importData,
  saveCustomer,
  saveUserEquipment,
  selectCustomerStaffList,
  selectEquipmentListById,
  selectUserDeviceList,
  updateStaffByCustomer
} from '@/api/admin/customer'
import { getRoomListByBuildIdsRq } from '@/api/admin/meeting/roomContent'
import { getCustomerContractList } from '@/api/admin/customerContract'
import CustomerContactsModal from './modules/CustomerContactsModal.vue'
import CustomerAttachmentList from './modules/CustomerAttachmentList.vue'
import pick from 'lodash.pick'
import { getParkList } from '@/api/admin/park'
import { getBuildingList } from '@/api/admin/building'
import { getBuildingDetailList } from '@/api/admin/buildingDetail'
import { getInfo } from '@/api/login'

let downloadLoadingInstance

export default {
  name: 'BaseForm',
  components: {
    CustomerContactsModal,
    CustomerAttachmentList
  },
  data() {
    return {
      id: '',
      defaultActiveKey: '1',
      // 合同行
      contractColumns: [
        {
          title: '合同编号',
          dataIndex: 'sn',
          scopedSlots: { customRender: 'sn' }
        },
        {
          title: '物管合同号',
          dataIndex: 'pmSn'
        },
        {
          title: '合同名称',
          dataIndex: 'name'
        },
        {
          title: '签订时间',
          dataIndex: 'signDate'
        },
        {
          title: '记租时间',
          dataIndex: 'startDate'
        },
        {
          title: '到期时间',
          dataIndex: 'endDate'
        },
        {
          title: '状态',
          dataIndex: 'status',
          scopedSlots: { customRender: 'status' }
        },
        {
          title: '签订人',
          dataIndex: 'operName'
        }
      ],
      // 联系人列表表头
      contactsItemColumns: [
        {
          title: '姓名',
          dataIndex: 'username'
        },
        {
          title: '手机号',
          dataIndex: 'mobile'
        },
        {
          title: '授权设备数量',
          dataIndex: 'num',
          scopedSlots: { customRender: 'num' }

        },

        {
          title: '性别',
          dataIndex: 'gender',
          scopedSlots: { customRender: 'gender' }

        },
        {
          title: '操作',
          key: 'operation',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      deviceColumns: [
        {
          title: '设备名称',
          dataIndex: 'equipmentName'
        },
        {
          title: '设备编号',
          dataIndex: 'equipmentNum'
        },
        {
          title: '所属地区',
          dataIndex: 'floorName',
          scopedSlots: { customRender: 'floorName' }

        }
      ],
      deviceData: [],
      labelColHalf: {
        span: 6
      },
      wrapperColHalf: {
        span: 18
      },
      labelColOneThird: {
        span: 9
      },
      wrapperColOneThird: {
        span: 15
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 21 }
      },
      contractData: [],
      orderPaymentData: [],
      orderRefundsData: [],
      orderShippingData: [],
      orderReturnsData: [],
      contactsItemData: [],

      queryParam:{
        keyword:''
      },
      selectedDeviceRowKeys: [],
      selectedRowKeys: [],
      uploadUrl: process.env.VUE_APP_API_BASE_URL + '/api/dfs/upload',
      headers: {
        Authorization: 'Bearer ' + storage.get(ACCESS_TOKEN)
      },
      fileList: [],
      previewVisible: false,
      previewImage: '',
      loading: false,
      imageUrl: '',
      userId: '',
      // form
      form: this.$form.createForm(this),
      file: '',
      visible: false,
      visible1: false,
      tenantList: [], // 地区
      parkList: [], // 园区
      buildingList: [], // 楼宇
      buildingDetailList: [], // 楼层
      roomList: [], //房间
      tenantEnable: false,
      parkEnable: false,
      mdl: {},
      customerId: null
    }
  },
  filters: {
    statusFilter(type) {
      const statusMap = {
        'DRAFT': '草稿',
        'APPROVING': '待审批',
        'APPROVED': '已审批',
        'REFUSE': '已拒绝',
        'EXECUTING': '执行中',
        'VOIDED': '已作废',
        'OVERDUE': '已到期',
        'END': '已结束'
      }
      return statusMap[type]
    }
  },
  created() {
    this.id = this.$route.query.customerId
    if (this.$route.query.types) {
      this.defaultActiveKey = '2'
    }
    this.handleInit()
    this.selectUserDeviceList()
    // 查询地区
    this.getTenantData()
    // 获取用户详细信息
    this.getUserDetail()
  },
  methods: {
    //查询企业用户数据
    searchData(){
      let param = {
        username:this.queryParam.keyword,
        customerId: this.$route.query.customerId
      }
      selectCustomerStaffList(param).then(res => {
        this.contactsItemData = res.rows
      })
    },

    // 获取用户详细信息
    getUserDetail() {
      getInfo().then(res => {
        console.log('getUserDetail', res)
        this.userDetail = res
        // 园区：5
        if (this.userDetail.roleIds && this.userDetail.roleIds.length > 0 && this.userDetail.roleIds[0] == 5) {
          //
          // 判断：是新增就查询园区
          const { customerId } = this.$route.query
          if (!customerId) {
            // 选择地区 -> 查询园区
            this.selectTenant(this.userDetail.tenantId)
            // 选择园区 -> 查询楼宇
            this.selectPark(this.userDetail.parkId)
          }
          //
          // 不可编辑
          this.tenantEnable = true
          this.parkEnable = true
          // 关联地区和园区
          this.mdl.parkId = this.userDetail.parkId
          this.mdl.tenantId = this.userDetail.tenantId
          this.form.setFieldsValue({
            parkId: this.mdl.parkId,
            tenantId: this.mdl.tenantId
          })
        }
      })
    },
    // 查询地区
    getTenantData() {
      getTenantList().then(res => {
        this.tenantList = res.rows
      })
    },
    // 选择地区 -> 查询园区
    selectTenant(id) {
      console.log('selectTenant', id)
      // 清空数据
      this.mdl.parkId = null // 园区
      this.mdl.buildingId = null // 楼宇
      this.mdl.buildingDetailIds = [] // 楼层
      this.mdl.roomIds = [] // 所属房间

      this.form.setFieldsValue({
        parkId: null, // 园区
        buildingId: null, // 楼宇
        buildingDetailIds: [], // 楼层
        roomIds: [] // 所属房间
      })
      // 查询园区
      getParkList({
        tenantId: id
      }).then(res => {
        this.parkList = res.rows
      })
    },
    // 选择园区 -> 查询楼宇
    selectPark(id) {
      // 清空数据
      this.mdl.buildingId = null // 楼宇
      this.mdl.buildingDetailIds = [] // 楼层
      this.mdl.roomIds = [] // 所属房间

      this.form.setFieldsValue({
        buildingId: null, // 楼宇
        buildingDetailIds: [], // 楼层
        roomIds: [] // 所属房间
      })
      // 查询楼宇
      getBuildingList({
        parkId: id
      }).then(res => {
        this.buildingList = res.rows
      })
    },
    // 选择楼宇 -> 查询楼层
    selectBuilding(id) {
      // 清空数据
      this.mdl.buildingDetailIds = [] // 楼层
      this.mdl.roomIds = [] // 所属房间

      this.form.setFieldsValue({
        buildingDetailIds: [], // 楼层
        roomIds: [] // 所属房间
      })
      // 查询楼层
      getBuildingDetailList({
        buildingId: id
      }).then(res => {
        this.buildingDetailList = res.rows
      })
    },
    // 选择楼层 -> 查询房间
    selectBuildingDetail(buildingDetailId) {
      console.log('buildingDetailId', buildingDetailId)
      // 查询房间
      this.getRoomListByFloorIdMethod(buildingDetailId)
    },
    // 查询房间
    getRoomListByFloorIdMethod(buildingDetailIds) {
      // 清空数据
      this.mdl.roomIds = [] // 所属房间

      this.form.setFieldsValue({
        roomIds: [] // 所属房间
      })
      //
      let type = 0
      // 河南建安
      const { customerId } = this.$route.query
      if (customerId == 83) {
        type = null
      }
      // 查询房间
      getRoomListByBuildIdsRq({
        'customerId': this.customerId,
        'buildingDetailIds': buildingDetailIds,
        'type': type
      }).then((res) => {
        this.roomList = res.data
      })
    },
    //获取设备数量
    handleDeviceTable(record) {
      this.visible1 = true
      this.userId = record.id
      selectEquipmentListById({ userId: record.id }).then(res => {
        if (res.data) {
          this.selectedDeviceRowKeys = res.data.map(d => d.id)
          this.selectedRowKeys = res.data
        } else {
          this.selectedDeviceRowKeys = []
          this.selectedRowKeys = []
        }
      })

    },
    //设备选中事件
    onDeviceSelectChange(selectedRowKeys, selectedRows) {
      this.selectedDeviceRowKeys = selectedRowKeys
      this.selectedRowKeys = selectedRows

    },
    itemHandleOk() {
      saveUserEquipment(
        {
          userId: this.userId,
          userIds: this.selectedDeviceRowKeys
        }
      ).then(res => {
        this.getContastsList()
        this.visible1 = false
        this.$message.success(res.msg)
      })
    },
    //获取所有设备
    selectUserDeviceList() {
      selectUserDeviceList().then(res => {
        this.deviceData = res.data
      })
    },
    exportTemplate() {
      const baseURL = process.env.VUE_APP_API_BASE_URL
      window.open(`${baseURL}/admin/staff/exportTemplate`)
    },


    customRequest(file) {
      // file 是上传的文件 其内容会在放在下面截图中
      // 后端需要接受的参数是 formData数据，
      // uploadFile 我自己的接口
      let customerId = this.$route.query.customerId
      const formData = new FormData()
      formData.append('file', file.file)
      console.log(file)
      importData(formData, customerId).then(res => {
        if (res.code == 0) {
          // 调用组件内方法, 设置为成功状态
          file.onSuccess(res, file.file)
          file.status = 'done'
          this.visible = false
          this.$message.success(res.data)
          this.getContastsList()
        } else {
          this.$message.error(res.msg)
          file.onError()
          file.status = 'error'
          this.getContastsList()
        }
      })
    },

    handleFileChange(info) {
      this.fileList = info.fileList

      if (info.file.status === 'done') {
        const result = info.file.response
        this.file = info.file.response
        this.fileName = result.fileName
      }
    },
    customChange() {

    },
    //导入用户数据
    importUser() {
      this.visible = true
    },
    handleFileOk() {
      importData({ file: this.file }).then(res => {
      })
    },
    handleDetail(id) {
      this.$router.push({
        name: 'customerContractDetailModal',
        query: { id: id, customerId: this.$route.query.customerId, url: 'customerEdit' }
      })
    },
    navContract(e) {
      this.$router.push({ name: 'customerContractEdit', query: { customerId: this.id, url: 'customerEdit' } })
    },
    onChangeBlacklist(checked) {
      this.mdl.isBlacklist = checked
    },
    getQiXinBasicInfo() {
      var keyword = this.form.getFieldValue('creditNo')
      getQiXinBasicInfo({ 'keyword': keyword }).then(res => {
        if (res.code === 0) {
          var qiXinResult = JSON.parse(res.data)
          if (!(isNaN(qiXinResult) && !isNaN(Date.parse(qiXinResult.endDate)))) {
            qiXinResult.endDate = null
          }
          this.form.setFieldsValue(pick(qiXinResult, 'creditNo', 'regNo', 'status', 'orgNo', 'operName', 'econKind', 'startDate', 'registCapi', 'endDate', 'address', 'scope', 'delFlag', 'belongOrg', 'remark'))
        } else {
          this.$message.error('同步工商信息失败：' + res.msg)
        }
      })
    },
    handleInit() {
      const { customerId } = this.$route.query
      this.customerId = customerId
      if (customerId) {
        getCustomer(customerId).then(res => {
          this.mdl = Object.assign(this.mdl, res)
          let copyMdl = JSON.parse(JSON.stringify(this.mdl))
          // 头像
          if (this.mdl.headImg) {
            this.imageUrl = process.env.VUE_APP_API_BASE_URL + this.mdl.headImg
          }
          // 照片墙
          this.mdl.bannerImages.forEach((item, i) => {
            item.url = process.env.VUE_APP_API_BASE_URL + item.url
          })
          this.fileList = this.mdl.bannerImages
          // 选择地区 -> 查询园区
          if (copyMdl.tenantId) {
            this.mdl = JSON.parse(JSON.stringify(copyMdl))
            this.selectTenant(copyMdl.tenantId)
          }
          // 选择园区 -> 查询楼宇
          if (copyMdl.parkId) {
            this.mdl = JSON.parse(JSON.stringify(copyMdl))
            this.selectPark(copyMdl.parkId)
          }
          // 选择楼宇 -> 查询楼层
          if (copyMdl.buildingId) {
            this.mdl = JSON.parse(JSON.stringify(copyMdl))
            this.selectBuilding(copyMdl.buildingId)
          }
          // 选择楼层 -> 查询房间
          if (copyMdl.buildingDetailIds) {
            this.mdl = JSON.parse(JSON.stringify(copyMdl))
            this.getRoomListByFloorIdMethod(copyMdl.buildingDetailIds, copyMdl.roomIds)
          }
          // 防止替换
          this.mdl = JSON.parse(JSON.stringify(copyMdl))
          //
          this.form.setFieldsValue(pick(this.mdl, 'id', 'name', 'shortName', 'type', 'customerStatus',
            'sector', 'country', 'process', 'contacts', 'phone', 'email', 'creditNo', 'mailAddress',
            'postalCode', 'channelType', 'channelName', 'isBlacklist', 'regNo', 'status', 'orgNo',
            'operName', 'econKind', 'startDate', 'registCapi', 'endDate',
            'address', 'scope', 'delFlag', 'belongOrg', 'remark', 'headImg', 'bannerImages',
            'roomId', 'buildId', 'roomIds', 'buildingDetailIds', 'tenantId', 'parkId',
            'buildingId'))
          //
        })
      }
      this.getContastsList()
      this.getContractList()
    },
    onChange(date, dateString) {
      console.log(date, dateString)
    },
    // handler
    handleSubmit(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          // eslint-disable-next-line no-console
          const bannerImages = []
          this.fileList.forEach((file, index) => {
            // 添加原来的
            if (file.hasOwnProperty('name') && file.hasOwnProperty('url') && file.hasOwnProperty('uid')) {
              bannerImages.push({ 'name': file.name, 'url': file.name, 'uid': index })
            }
            if (file.status === 'done' && file.response.code === 0) {
              const data = file.response
              bannerImages.push({ 'name': data.fileName, 'url': data.fileName, 'uid': index })
            }
          })
          // 照片墙
          values.bannerImages = bannerImages
          console.log('Received values of form: ', values)
          // values.startDate = moment(values.startDate).format('YYYY-MM-DD')
          // console.log(values.startDate)
          this.confirmLoading = true
          saveCustomer(values).then(res => {
            if (res.code === 0) {
              this.$message.success('保存成功')
              this.$emit('ok')
              this.visible = false
              this.rollback()
            } else {
              this.$message.error(res.msg)
            }
          }).catch(() => {
            this.$message.error('系统错误，请稍后再试')
          }).finally(() => {
            this.confirmLoading = false
          })
        }
      })
    },
    rollback() {
      this.$router.push('/admin/service/customer')
    },
    // 联系人列表
    getContastsList() {
      let param = {
        customerId: this.$route.query.customerId
      }
      selectCustomerStaffList(param).then(res => {
        this.contactsItemData = res.rows
      })
    },
    // 合同列表
    getContractList() {
      getCustomerContractList({ customerId: this.$route.query.customerId }).then(res => {
        // console.log(res)
        if (res.code === 0) {
          this.contractData = res.rows
        }
      })
    },
    // 新增联系人回调
    handleContactSaved() {
      this.getContastsList()
    },
    // 删除联系人
    handleDeleteContact(contactInfo) {
      console.log(contactInfo)
      contactInfo.icsCustomerId = this.$route.query.customerId
      // contactInfo.
      updateStaffByCustomer(contactInfo).then(res => {
        if (res.code === 0) {
          this.$message.success('删除成功')
          this.deleteVisible = false
          this.getContastsList()
        } else {
          this.$message.error(res.msg)
        }
      }).catch(() => {
        this.$message.error('系统错误，请稍后再试')
      }).finally(() => {
      })
    },

    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJpgOrPng) {
        this.$message.error('You can only upload JPG file!')
      }
      const isLt2M = file.size / 1024 / 1024 < 10
      if (!isLt2M) {
        this.$message.error('图片必须小于 10MB!')
      }
      return isJpgOrPng && isLt2M
    },
    handleChange(info) {
      if (info.file.status === 'uploading') {
        this.loading = true
        return
      }
      if (info.file.status === 'done') {
        const { form: { setFieldsValue } } = this
        const result = info.file.response
        // 设置值
        this.$nextTick(() => {
          setFieldsValue({
            headImg: result.fileName
          })
        })
        // Get this url from response in real world.
        getBase64(info.file.originFileObj, imageUrl => {
          this.imageUrl = imageUrl
          this.loading = false
        })
      }
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64FileList(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },
    handleCancel() {
      this.previewVisible = false
    },
    // 上传照片墙
    handleChangeFileList({ fileList }) {
      this.fileList = fileList
    }
  }
}

// 上传头像
function getBase64(img, callback) {
  const reader = new FileReader()
  reader.addEventListener('load', () => callback(reader.result))
  reader.readAsDataURL(img)
}

// 上传照片墙
function getBase64FileList(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = error => reject(error)
  })
}
</script>

<style>
.avatar-uploader > .ant-upload {
  width: 102px;
  height: 102px;
}

.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
